<template>
  <div class="dashboard">
    <div class="header">
      <h1>高校开放实验室预约管理系统</h1>
    </div>

    <div class="charts-container">
      <div class="chart-card">
        <h3>预约趋势</h3>
        <div ref="bookingTrendChart" class="chart"></div>
      </div>

      <div class="chart-card">
        <h3>快速审批</h3>
        <el-table
          :data="bookingHistory"
          height="300"
          border
          style="width: 100%">
          <el-table-column
            prop="applyTime"
            label="开始时间"
            sortable
            width="180">
          </el-table-column>
          <el-table-column
            prop="auditTypeDesc"
            label="审批类型"
            width="180">
          </el-table-column>
          <el-table-column
            prop="userName"
            label="姓名">
          </el-table-column>
          <el-table-column
            prop="statusDesc"
            label="审批状态">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100">
            <template slot-scope="scope">
              <el-button @click="auditPass(scope.row)" type="text" size="small">审批通过</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="chart-card">
        <h3>实验室使用率</h3>
        <div ref="labUsageChart" class="chart"></div>
      </div>

      <div class="chart-card">
        <h3>预约类型分布</h3>
        <div ref="bookingTypeChart" class="chart"></div>
      </div>

      <div class="chart-card">
        <h3>预约时段分布</h3>
        <div ref="bookingTimeChart" class="chart"></div>
      </div>

    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {listAudit} from "@/api/system/audit";
import {delAppointment} from "@/api/system/appointment";
import {auditReservation} from "@/api/system/reservation";
import {auditLabBorrow} from "@/api/system/labBorrow";

export default {
  data() {
    return {
      dateRange: [],
      bookingTrendChart: null,
      labUsageChart: null,
      bookingTypeChart: null,
      bookingTimeChart: null,
      bookingHistory: [],
    };
  },
  mounted() {
    this.initCharts();
    this.fetchData();
    this.getAllAudit();
  },
  beforeDestroy() {
    this.bookingTrendChart.dispose();
    this.labUsageChart.dispose();
    this.bookingTypeChart.dispose();
    this.bookingTimeChart.dispose();
  },
  methods: {
    initCharts() {
      this.bookingTrendChart = echarts.init(this.$refs.bookingTrendChart);
      this.labUsageChart = echarts.init(this.$refs.labUsageChart);
      this.bookingTypeChart = echarts.init(this.$refs.bookingTypeChart);
      this.bookingTimeChart = echarts.init(this.$refs.bookingTimeChart);

      // 窗口大小变化时重新调整图表大小
      window.addEventListener('resize', this.resizeCharts);
    },
    auditPass(row) {
      // 审批通过
      this.$modal.confirm('是否确认通过该申请').then(function () {
        if (row.auditType === 1) {
          if (row.audit === 0) {
            auditLabBorrow({
              id: row.id,
              audit: 1
            }).then(res => {
              this.getAllAudit();
              this.$modal.msgSuccess(res.msg);
            })
          } else if (row.audit === 1) {
            auditLabBorrow({
              id: row.id,
              audit: 2
            }).then(() => {
              this.getAllAudit();
              this.$modal.msgSuccess(res.msg);
            })
          }
        } else {
          if (row.audit === 0) {
            auditReservation({
              id: row.id,
              audit: 1
            }).then(() => {
              this.getAllAudit();
              this.$modal.msgSuccess(res.msg);
            })
          } else if (row.audit === 1) {
            auditReservation({
              id: row.id,
              audit: 2
            }).then(() => {
              this.getAllAudit();
              this.$modal.msgSuccess("审批成功");
            })
          }
        }
      }).then(() => {
        this.getAllAudit();
        this.$modal.msgSuccess("已完成");
      }).catch(() => {
      });
    },
    getAllAudit() {
      listAudit().then(res =>{
        this.bookingHistory = res.data;
      })
    },
    resizeCharts() {
      this.bookingTrendChart.resize();
      this.labUsageChart.resize();
      this.bookingTypeChart.resize();
      this.bookingTimeChart.resize();
    },
    fetchData() {
      // 模拟数据，实际项目中可以通过 API 获取
      this.updateBookingTrendChart(this.generateMockData());
      this.updateLabUsageChart(this.generateMockData());
      this.updateBookingTypeChart(this.generateMockData());
      this.updateBookingTimeChart(this.generateMockData());
    },
    generateMockData() {
      // 模拟数据生成
      return {
        bookingTrend: {
          dates: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          counts: [120, 150, 130, 180, 200, 160, 100],
        },
        labUsage: {
          labs: ['实验室A', '实验室B', '实验室C', '实验室D'],
          usageRates: [85, 70, 90, 65],
        },
        bookingTypes: {
          types: ['教学', '科研', '培训', '其他'],
          counts: [120, 80, 40, 30],
        },
        bookingTime: {
          timeSlots: ['08:00-10:00', '10:00-12:00', '14:00-16:00', '16:00-18:00'],
          counts: [40, 60, 80, 50],
        },
      };
    },
    updateBookingTrendChart(data) {
      const option = {
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: data.bookingTrend.dates,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: data.bookingTrend.counts,
            type: 'line',
            smooth: true,
            itemStyle: {
              color: '#5470c6',
            },
          },
        ],
      };
      this.bookingTrendChart.setOption(option);
    },
    updateLabUsageChart(data) {
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}%',
        },
        series: [
          {
            name: '实验室使用率',
            type: 'pie',
            radius: ['40%', '70%'],
            data: data.labUsage.labs.map((lab, index) => ({
              name: lab,
              value: data.labUsage.usageRates[index],
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      };
      this.labUsageChart.setOption(option);
    },
    updateBookingTypeChart(data) {
      const option = {
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: data.bookingTypes.types,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: data.bookingTypes.counts,
            type: 'bar',
            itemStyle: {
              color: '#91cc75',
            },
          },
        ],
      };
      this.bookingTypeChart.setOption(option);
    },
    updateBookingTimeChart(data) {
      const option = {
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: data.bookingTime.timeSlots,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: data.bookingTime.counts,
            type: 'line',
            itemStyle: {
              color: '#fac858',
            },
          },
        ],
      };
      this.bookingTimeChart.setOption(option);
    },
    handleDateChange() {
      // 根据日期范围筛选数据
      console.log('Date range changed:', this.dateRange);
      // 实际项目中可以通过 API 获取筛选后的数据
      this.fetchData();
    },
  },
};
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.chart-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chart {
  height: 300px;
  width: 100%;
}

.booking-history {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.quick-booking {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

</style>
